import json
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad


def vn_function(key_str):
    """
    将输入字符串转换为16字节的密钥
    相当于JavaScript中的Vn函数
    """
    # 将字符串转换为UTF-8字节
    utf8_bytes = key_str.encode('utf-8')

    # 创建16字节的数组，不足的用0填充
    result = bytearray(16)
    for i in range(min(len(utf8_bytes), 16)):
        result[i] = utf8_bytes[i]

    return bytes(result)


def decrypt_data(encrypted_str, key_str="fsdfjk12390jqIOJSDKL"):
    """
    解密函数，相当于JavaScript中的Xn函数

    参数:
        encrypted_str: 加密的字符串（URL安全的Base64格式）
        key_str: AES密钥

    返回:
        解密后的JSON对象
    """
    # 如果输入为空或不是字符串，直接返回
    if not encrypted_str or not isinstance(encrypted_str, str):
        return encrypted_str

    try:
        # 将URL安全的Base64转换为标准Base64
        standard_base64 = encrypted_str.replace('-', '+').replace('_', '/')

        # Base64解码
        encrypted_bytes = base64.b64decode(standard_base64)

        # 处理密钥
        key = vn_function(key_str)

        # 创建AES-ECB解密器
        cipher = AES.new(key, AES.MODE_ECB)

        # 解密并去除填充
        decrypted_bytes = unpad(cipher.decrypt(encrypted_bytes), AES.block_size)

        # 转换为UTF-8字符串
        decrypted_str = decrypted_bytes.decode('utf-8')

        # 解析JSON
        return json.loads(decrypted_str)
    except Exception as e:
        print(f"解密失败: {e}")
        return "{}"

if __name__ == "__main__":
    # 加密文案所在地址
    input_path = "./input/encrypted_data.txt"

    # 加密文案导出地址
    output_path = "./output/decrypted_data.json"

    # 读取加密文案
    with open(input_path, 'r', encoding='utf-8') as file:
        encrypted_data = file.read()

    # 解密数据
    decrypted_json = decrypt_data(encrypted_data)

    # 将解密后的JSON保存到文件
    with open(output_path, 'w', encoding='utf-8') as file:
        file.write(json.dumps(decrypted_json, indent=4, ensure_ascii=False))

    print(decrypted_json)